//
//  HSAudioRecorder.swift
//  HappyToSee
//
//  Created by Wade on 2024/6/29.
//

import Foundation
import AVFAudio

class HSAudioRecorder {
    var audioRecorder:AVAudioRecorder?
    var currentRecordURL:URL?
     init() {
        self.configure()
    }
    
    
    /// 初始化录音配置
    private func configure() {
        // 获取存放播放文件路径
        let audioFileURL = FilePathUtils.cachePathURL!.appendingPathComponent("record.m4a")
        currentRecordURL = audioFileURL
        // 设置声音的 session
        do {
            try AVAudioSession.sharedInstance().setCategory(.playAndRecord)
            // 录制器的配置：
            let recorderSetting: [String: Any] = [
                AVFormatIDKey: Int(kAudioFormatMPEG4AAC), // 储存音讯资料格式
                AVSampleRateKey: 44100.0, // 取样率
                AVNumberOfChannelsKey: 2, // 频道数
                AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue, // 声音品质
            ]
            // 初始化并准备录制器
            audioRecorder = try AVAudioRecorder(url: audioFileURL, settings: recorderSetting)
            audioRecorder!.isMeteringEnabled = true
            audioRecorder!.prepareToRecord()
        } catch {
            print(error)
        }
    }
}

extension HSAudioRecorder{
    func record() {
       
        if !audioRecorder!.isRecording {
            let audioSession = AVAudioSession.sharedInstance()
            do {
                try audioSession.setCategory(.playAndRecord,mode: .default)
                try audioSession.setActive(true)
                // 开始录制
                audioRecorder!.record()
                // ...
            } catch {
                print(error)
            }
        } else {
            // 暂停录制
            audioRecorder!.pause()
            // ...
        }
    }
    
   
    
    /// 暂停录音
    func pauseRecoder() {
        self.audioRecorder!.pause()
    }
    /// 结束录音
    func endRecoder() {
        // 停止
        audioRecorder!.stop()
        NSLog("RecordUR::" + self.currentRecordURL!.absoluteString)
    }
}


